<template>
  <div class="address-management">
    <el-row>
       <el-button type="text" class="back-button" @click="goBack">
         <el-icon><ArrowLeft /></el-icon>
         <span>返回</span>
       </el-button>
       <div class="panel-header">
          <h2 class="panel-title">收货地址管理</h2>
        </div>
    </el-row>
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <div class="address-list">
          <div
            v-for="address in addresses"
            :key="address.id"
            class="address-card"
          >
            <div class="address-info">
              <div class="receiver-info">
                <span class="receiver-name">{{ address.receiver }}</span>
                <span class="receiver-phone">{{ address.phone }}</span>
              </div>
              <div class="address-detail">
                {{ address.province }} {{ address.city }} {{ address.district }} {{ address.street }}
              </div>
            </div>
            <div class="address-actions">
              <el-button type="text" class="edit-btn" @click="editAddress(address)">修改</el-button>
              <el-button type="text" class="delete-btn" @click="deleteAddress(address.id)">删除</el-button>
            </div>
          </div>

          <!-- 添加新地址按钮 -->
          <div class="add-address-card" @click="addAddress()">
            <el-icon class="add-icon"><Plus /></el-icon>
            <span>添加新地址</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑地址对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingAddress ? '编辑地址' : '添加新地址'"
      width="500px"
      @closed="closeDialog()"
    >
      <el-form :model="addressForm" :rules="rules" ref="addressFormRef" label-width="80px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="addressForm.province" placeholder="请选择省份" style="width: 100%" @change="onProvinceChange">
            <el-option v-for="province in provinceOptions" :key="province.value" :label="province.label" :value="province.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="addressForm.city" placeholder="请选择城市" style="width: 100%" @change="onCityChange" :disabled="!addressForm.province">
            <el-option v-if="!addressForm.province" label="请先选择省份" value="" disabled />
            <el-option v-else v-for="city in cityOptions" :key="city.value" :label="city.label" :value="city.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="district">
          <el-select v-model="addressForm.district" placeholder="请选择区县" style="width: 100%" :disabled="!addressForm.city">
            <el-option v-if="!addressForm.province || !addressForm.city" label="请先选择省份" value="" disabled />
            <el-option v-else v-for="district in districtOptions" :key="district.value" :label="district.label" :value="district.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.street"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false;">取消</el-button>
          <el-button type="warning" @click="saveAddress(addressForm)">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { selectAddressMessage, deleteAddressMessage, updateAddressMessage,addAddressMessage } from '@/api/address'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import areaData from '@/utils/areaData.js'
import { useRouter } from 'vue-router'

const router = useRouter()

const userStore = useUserStore() // 初始化用户store

onMounted(() => {
  addressForm.uid = userStore.user.uid
  // 页面加载时获取用户地址列表
  queryPage()
})

//对话框的显示
const showAddDialog = ref(false)
const editingAddress = ref(null)
const addressFormRef = ref(null)

const queryPage = ()=>{
  selectAddressMessage(userStore.user.uid).then((res) => {
    // 处理返回的地址数据
    addresses.value = res.data
  })
}
const goBack = () => {
  router.back()
}
// 地址数据
const addresses = ref([])

// 表单数据
const addressForm = reactive({
  receiver: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  street: '',
  uid: 0
})

// 省市区选项
const provinceOptions = ref(areaData.map(province => ({
  value: province.value,
  label: province.label
})))

const cityOptions = ref([])
const districtOptions = ref([])

// 表单验证规则
const rules = {
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  district: [
    { required: true, message: '请选择区县', trigger: 'change' }
  ],
  street: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 省份变化时更新城市选项
const onProvinceChange = () => {
  if (addressForm.province) {
    const province = areaData.find(p => p.value === addressForm.province)
    if (province && province.children) {
      cityOptions.value = province.children.map(city => ({
        value: city.value,
        label: city.label
      }))
    } else {
      cityOptions.value = []
    }
  } else {
    cityOptions.value = []
  }
  // 重置城市和区县
  addressForm.city = ''
  addressForm.district = ''
  districtOptions.value = []
}

// 城市变化时更新区县选项
const onCityChange = () => {
  if (addressForm.province && addressForm.city) {
    const province = areaData.find(p => p.value === addressForm.province)
    if (province && province.children) {
      const city = province.children.find(c => c.value === addressForm.city)
      if (city && city.children) {
        districtOptions.value = city.children.map(district => ({
          value: district.value,
          label: district.label
        }))
      } else {
        districtOptions.value = []
      }
    } else {
      districtOptions.value = []
    }
  } else {
    districtOptions.value = []
  }
  // 重置区县
  addressForm.district = ''
}

// 点击修改的显示方法
const editAddress = (address) => {
  editingAddress.value = true
  addressForm.receiver = address.receiver
  addressForm.phone = address.phone
  addressForm.province = address.province
  addressForm.street = address.street
  addressForm.id = address.id
  // 编辑时设置对应的城市和区县选项
  if (address.province) {
    onProvinceChange()
     // 延迟设置城市和区县，确保城市选项已更新
     setTimeout(() => {
      if (address.city) {
        addressForm.city = address.city
        // 调用城市变化方法更新区县选项
        onCityChange()
        // 延迟设置区县，确保区县选项已更新
        setTimeout(() => {
          if ( address.district) {
            addressForm.district = address.district
          }
        }, 0)
      }
    }, 0)
  }
  showAddDialog.value = true
}
//点击添加的显示方法
const addAddress = () => {
  editingAddress.value = false
  resetForm()
  showAddDialog.value = true
}
//删除地址
const deleteAddress = (addressId) => {
 deleteAddressMessage(addressId).then((res) => {
    if (res.status === 200) {
      // 删除成功，刷新地址列表
      queryPage()
    } else {
      // 删除失败，提示用户
      ElMessage.error('删除地址失败，请稍后重试')
    }
  })
}

// 保存地址
const saveAddress = (formData) => {
  addressFormRef.value.validate((valid) => {
    if (valid) {
      if (editingAddress.value) {
        // 编辑地址
      updateAddressMessage(formData).then((res) => {
        if (res.status === 200) {
          // 编辑成功，刷新地址列表
          queryPage()
        } else {
          // 编辑失败，提示用户
          ElMessage.error(res.message)
        }
      })
      } else {
        // 新增地址
        addAddressMessage(formData).then((res) => {
          if (res.status === 200) {
            // 新增成功，刷新地址列表
            queryPage()
          } else {
            // 新增失败，提示用户
            ElMessage.error(res.message)
          }
        })
      }
      // 新增或编辑成功后,关闭对话框并重置表单
      closeDialog()
    }
  })
}
// 关闭对话框时重置表单
const closeDialog = () => {
  showAddDialog.value = false
  resetForm()
}
// 重置表单
const resetForm = () => {
  Object.assign(addressForm, {
    receiver: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    street: ''
  })
  editingAddress.value = null
  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }
  // 重置选项
  cityOptions.value = []
  districtOptions.value = []
}
</script>

<style scoped>
.panel-header {
  margin-left: 20px;
}

.panel-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.back-button {
  margin-left: 150px;
  color: #FF8C00 !important;
  font-size: 16px;
}

.back-button .el-icon {
  margin-right: 5px;
}

.address-management {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

/* Header */
.header {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-content {
  display: flex;
  align-items: center;
  padding: 15px 0;
  gap: 30px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.brand-name {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

.page-title h2 {
  color: white;
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

/* Main Content */
.main-content {
  padding: 30px 0;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.address-card {
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s;
}

.address-card:hover {
  border-color: #ff8c00;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.receiver-info {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
}

.receiver-name {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.receiver-phone {
  color: #666;
  font-size: 14px;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
}

.address-actions {
  display: flex;
  gap: 15px;
}

.edit-btn {
  color: #ff8c00 !important;
}

.delete-btn {
  color: #e74c3c !important;
}

.add-address-card {
  border: 2px dashed #d0d0d0;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  color: #999;
  background: white;
}

.add-address-card:hover {
  border-color: #ff8c00;
  color: #ff8c00;
}

.add-icon {
  font-size: 32px;
  margin-bottom: 10px;
  display: block;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }

  .header-content {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>